//------------------------------------------------------------------------------
// <copyright file="RpcMessage.cpp" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

#include "stdafx.h"

#include "RpcMessage.h"
#include <ObjBase.h>

using namespace Microsoft::Internal::GamesTest::Rpc::Server;

const wchar_t PayloadKey[] = L"payload";
const wchar_t MessageTypeKey[] = L"messageType";

GAMESTEST_ANNOTATE_HRESULT_METHOD HRESULT RpcMessage::Parse(const std::wstring& data, RpcMessage* result)
{
	HRESULT hr = S_OK;

	VERIFY_PARAM_NOT_NULL(result);

	try
	{
		JsonNode jsonMessage;
		jsonMessage.Parse(JsonString(data));

		result->messageType = (MessageType)jsonMessage.GetIntegerValue(MessageTypeKey);
		result->payload = jsonMessage.GetStringValue(PayloadKey);
	}
	catch (std::out_of_range)
	{
		// Key doesn't exist error
		hr = E_INVALID_PROTOCOL_FORMAT;
		goto end;
	}
	catch (std::invalid_argument)
	{
		// Parse error
		hr = E_INVALID_PROTOCOL_FORMAT;
		goto end;
	}

end:
	return hr;
}

GAMESTEST_ANNOTATE_HRESULT_METHOD HRESULT RpcMessage::Serialize(std::wstring& serializedData)
{
	JsonNode jsonMessage;
	jsonMessage.SetValue(PayloadKey, payload);
	jsonMessage.SetValue(MessageTypeKey, messageType);

	serializedData = jsonMessage.Serialize();

	return S_OK;
}